package org.example.rabbitmq.myTool;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQUtils {

    private static final String QUEUE_NAME = "hello";
    private static ConnectionFactory factory;
    private static Connection connection;

    static {
        factory = new ConnectionFactory();
        factory.setHost("localhost");
        try {
            connection = factory.newConnection();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    public static void send(String message) {
        try {
            Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
            channel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void receive() throws IOException, TimeoutException {

        Channel channel = null;
        if (!connection.isOpen()) {
            connection = factory.newConnection();
        }
        try {
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            channel.basicConsume(QUEUE_NAME, true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery delivery) throws IOException {
                    System.out.println("收到消息是" + new String(delivery.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) {
                    System.out.println("接受失败了...");
                }
            });
            System.out.println("开始接受消息");
            System.in.read();
//            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.close();        //关闭通道后重新打开, 管理界面的端口号没有改变, 连接复用
//                closeConnection();    //关闭连接后重新打开, 管理界面的端口号改变了, 连接没有复用
                System.out.println("关闭通道连接");
            }
        }
    }

    public static void closeConnection() {
        try {
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

